package com.qf.shiroboot.service.impl;

import com.qf.shiroboot.entity.User;
import com.qf.shiroboot.service.UserService;
import org.springframework.stereotype.Service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

@Service
public class UserServiceImpl implements UserService {


    @Override
    public User findByUsername(String username) {
        try {
            //1. 注册驱动
            Class.forName("com.mysql.jdbc.Driver");

            //2. 获取连接对象
            Connection connection = DriverManager.getConnection("jdbc:mysql:///shiro", "root", "root");

            //3. 声明SQL
            String sql = "select id,username,password,salt,nickname from users where username = ?";

            //4. 预执行SQL，设置参数
            PreparedStatement ps = connection.prepareStatement(sql);
            ps.setObject(1,username);

            //5. 执行SQL获取返回结果
            ResultSet rs = ps.executeQuery();

            //6. 遍历返回结果并封装对象
            User user = null;
            while(rs.next()){
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setPassword(rs.getString("password"));
                user.setSalt(rs.getString("salt"));
                user.setNickname(rs.getString("nickname"));
            }
            //7. 释放资源
            rs.close();
            ps.close();
            connection.close();
            //8. 返回数据
            return user;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}